package com.egdigital.allzic.ui.fragment;

import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.costum.android.widget.LoadMoreListView;
import com.costum.android.widget.LoadMoreListView.OnLoadMoreListener;
import com.egdigital.allzic.R;
import com.egdigital.allzic.data.json.JsonCallBack;
import com.egdigital.allzic.data.json.JsonParserCity;
import com.egdigital.allzic.data.json.VolleyManager;
import com.egdigital.allzic.data.object.Country;
import com.egdigital.allzic.ui.activity.ActivityMain;
import com.egdigital.allzic.ui.adapter.AdapterCity;
import com.egdigital.allzic.utils.NetworkManager;

public class FragmentExploreCity extends BaseMainFragment implements OnItemClickListener, OnClickListener {

	private static final String	TAG				= FragmentExploreCity.class.getSimpleName();				// log
	private static String		URL_CITY		= "http://www.allzicradio.com/json/get_cities/%s/%s/%s";
	private int					mPage			= 0;
	private static final int	COUNT_BY_PAGE	= 50;
	private JsonParserCity		mJsonParser;
	private List<String>		mListCity;
	private AdapterCity			mAdapter;
	//
	private Country				mCountry;
	private LoadMoreListView	mListView;
	private TextView			mTitle;
	private ImageButton			mcloseButton;
	// network ui
	protected ActivityMain		mParent;
	protected View				mView;

	/**
	 * life cycle
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try {
			mCountry = getArguments().getParcelable("country");
		} catch (Exception e) {
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_list_city, container, false);
		mLoadingView = (RelativeLayout) mView.findViewById(R.id.fragment_city_loading);
		mReloadView = (LinearLayout) mView.findViewById(R.id.fragment_city_reload);
		mNoResultView = (TextView) mView.findViewById(R.id.fragment_city_noresult);
		//
		mListView = (LoadMoreListView) mView.findViewById(R.id.fragment_city_list);
		mTitle = (TextView) mView.findViewById(R.id.fragment_city_title);
		mcloseButton = (ImageButton) mView.findViewById(R.id.fragment_city_close);
		return mView;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		mView.setOnTouchListener(new View.OnTouchListener() {

			public boolean onTouch(View v, MotionEvent event) {
				return true;
			}
		});
		mListView.setOnItemClickListener(this);
		mTitle.setText(mCountry.getTitle());
		mcloseButton.setOnClickListener(this);
		mReloadView.setOnClickListener(this);
		super.onViewCreated(view, savedInstanceState);
	}

	@Override
	public void onResume() {
		super.onResume();
		if (mParent != null) {
			VolleyManager.init(mParent);
		}
		if (mJsonParser == null) {
			mJsonParser = JsonParserCity.getInstance();
		}
		setUpCallbacks();
		if (mParent != null) {
			mJsonParser.initAndStartRequestQueue();
		}
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
		FragmentCategoryRadio fragment = new FragmentCategoryRadio();
		Bundle param = new Bundle();
		param.putString("city", mListCity.get(position));
		fragment.setArguments(param);
		mParent.getSupportFragmentManager()
				.beginTransaction()
				.setCustomAnimations(R.anim.slide_in_bottom, R.anim.slide_out_top, R.anim.slide_in_top, R.anim.slide_out_bottom)
				.add(R.id.fragment_explore, fragment)
				.addToBackStack("1")
				.commit();
	}

	/**
	 * fragment life cycle
	 */
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mParent = (ActivityMain) activity;
	}

	@Override
	public void onDetach() {
		super.onDetach();
		mParent = null;
		if (mJsonParser != null) {
			mJsonParser.stopRequestQueue();
		}
	}

	/**
	 * methods
	 */
	private void loadData() {
		if (NetworkManager.isConnected(mParent.getApplicationContext())) {
			mJsonParser.extractJsonObjectData(String.format(URL_CITY, mCountry.getId(), mPage, COUNT_BY_PAGE));
		} else {
			mListView.setVisibility(View.GONE);
		}
	}

	private void setUpCallbacks() {
		mListView.setOnLoadMoreListener(new OnLoadMoreListener() {

			@Override
			public void onLoadMore() {
				mPage++;
				mJsonParser.extractJsonObjectData(String.format(URL_CITY, mCountry.getId(), mPage, COUNT_BY_PAGE));
			}
		});
		mJsonParser.setJsonCallBack(new JsonCallBack() {

			public void downloadStarted() {
				Log.i(TAG, "downloadStarted");
				mListView.setVisibility(View.GONE);
				setLoading(mListView);
			}

			public void downloadPercent(int percent) {
				if (mLoadingView != null) {
					TextView textViewPercent = (TextView) mLoadingView.findViewById(R.id.loading_percent);
					textViewPercent.setText(percent + "%");
				}
			}

			public <T> void downloadCompleted(List<T> list) {
				Log.i(TAG, "downloadCompleted");
				if (mParent == null || list == null) {
					return;
				}
				if (!list.isEmpty()) {
					Log.i(TAG, "" + (List<String>) list);
					setLoaded(mListView);
					mListCity = (List<String>) list;
					updateAdapter((List<String>) list);
				} else {
					mListView.setVisibility(View.GONE);
				}
				mListView.onLoadMoreComplete();
			}

			@Override
			public void downloadEndedWithError(VolleyError error) {
				mListView.setVisibility(View.GONE);
			}
		});
	}

	private void updateAdapter(List<String> list) {
		if (mAdapter == null) {
			mAdapter = new AdapterCity(mParent.getApplicationContext(), (List<String>) list);
			mListView.setAdapter(mAdapter);
			mListView.setSelection(0);
		} else {
			mAdapter.setData((List<String>) list);
			mAdapter.notifyDataSetChanged();
		}
		mListView.setVisibility(View.VISIBLE);
		mListView.setOnItemClickListener(this);
	}

	/**
	 * animation
	 */
	@SuppressLint("NewApi")
	@Override
	public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
		Animation animation = super.onCreateAnimation(transit, enter, nextAnim);
		if (animation == null && nextAnim != 0) {
			animation = AnimationUtils.loadAnimation(getActivity(), nextAnim);
		}
		if (animation != null) {
			animation.setAnimationListener(new AnimationListener() {

				public void onAnimationEnd(Animation animation) {
					getView().post(new Runnable() {

						@Override
						public void run() {
							loadData();
						}
					});
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				@Override
				public void onAnimationStart(Animation animation) {
				}
			});
		}
		return animation;
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
			case R.id.fragment_city_close:
				mParent.removeFragment();
				break;
			case R.id.fragment_city_reload:
				loadData();
				break;
		}
	}
}
